package com.rao.gmall.product.config;


import com.rao.gmall.common.config.ItemRedissonConfig;
import com.rao.gmall.common.handler.GlobalExceptionHandler;
import lombok.Data;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.*;

//  第二步： 加载 布隆过滤器对象初始化的类，自动注入，供 SkuInfoServiceImpl 添加 sku 时让布隆过滤器添加占位;
// 定义属于自己得业务线程池（不要抽取，业务可能不同需求不同）
@Import({ItemRedissonConfig.class, GlobalExceptionHandler.class})
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Configuration
public class ProductConfig {

    // 将自定义类作为参数传入自定义的业务线程池，且将线程池命名为 corePool
    @Bean("corePool")
    public ThreadPoolExecutor executor(ThreadConfigProperties properties) {
        return new ThreadPoolExecutor(properties.core,
                properties.max,
                properties.keepalive,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(properties.queueLength),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }

    // 读取配置文件的属性并创建 set、get 方法
    @Data
    @Component
    @ConfigurationProperties(prefix = "product-service.thread")
    class ThreadConfigProperties {
        private int core;
        private int max;
        private Long keepalive;
        private int queueLength;
    }

    // 自定义线程池的名字
    class MyItemServiceThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread();
            thread.setName("product-service:" + UUID.randomUUID().toString().substring(0, 5));
            return thread;
        }
    }
}
